const Path = require('path');
var ejsExcel = require("ejsexcel");
var fs = require("fs");
const superagent = require('superagent')
const cheerio = require("cheerio")
var encoding = require("encoding")

require('superagent-charset')(superagent)

function isChinese(temp) {
    // var re = /[^/u4e00-/u9fa5]/;
    // if (re.test(temp)) return false;
    // return true;
    if (escape(temp).indexOf("%u") < 0) {
        return false;
    } else {
        return true;
    }
}

function textHandler(string) {
    var _string = string
    if (!isChinese(_string)) {
        if (_string.indexOf(' ') > 0) {
            _string = _string.split(" ")[0]
        }
    }
    if (_string.indexOf("（")) {
        _string = _string.split("（")[0]
    }
    if (_string.indexOf("[")) {
        _string = _string.split("[")[0]
    }
    if (_string.indexOf(".")) {
        _string = _string.split(".")[0]
    }

    return _string
}

let exportWeekReport = {
    config: {
        description: '图书添加',
        cors: {
            origin: ['*'],
            additionalHeaders: ['cache-control', 'x-requested-with']
        }
    },
    method: 'post',
    path: '/book/importBook',
    handler: async (request, h) => {

        let request_body = request.payload

        let stateCode;
        let stateMessage;

        let result = {
            data: {
                bookName: "",
                auth: ""
            },
            stateCode: '',
            stateMessage: ''
        }
        let promise = function () {
            return new Promise((resolve, reject) => {
                // 京东
                var url = request_body.url
                var urlText = url.text
                var urlType = url.type
                try {
                    superagent.get(urlText)
                        .charset('gbk')
                        .end((err, res) => {
                            if (err) {
                                reject(err)
                            }
                            var $ = cheerio.load(res.text)

                            var bookName
                            if ($('.sku-name').text()) {
                                bookName = $('.sku-name').text().replace(/(^\s*)|(\s*$)/g, "")
                            } else {
                                reject('此书无法识别')
                            }
                            // result.data.bookName = textHandler(bookName)
                            result.data.bookName = bookName
                            var nodes
                            if ($('.p-author')[0]) {
                                nodes = $('.p-author')[0].childNodes
                                for (let index = 0; index < nodes.length; index++) {
                                    const element = nodes[index];
                                    if (element.tagName === "a") {
                                        var auth = element.attribs["data-name"]
                                        // result.data.auth = textHandler(auth)
                                        result.data.auth = auth
                                        break;
                                    }
                                }
                            } else {
                                reject('此书无法识别')
                                return
                            }
                            // result.data.introduction = $('#p-ad').text().replace(/(^\s*)|(\s*$)/g, "")
                            // result.data.introduction = textHandler(introduction)
                            resolve(result)
                        })
                } catch (error) {
                    console.log(error)
                    reject(error)
                }

            })
        }
        return await promise()
    }
}

module.exports = exportWeekReport